<?php
declare (strict_types = 1);

namespace app;

use app\common\model\MasterModel;
use app\common\model\MerchantModel;
use app\common\model\SysManagerModel;
use app\common\model\UserModel;
use app\common\model\WebsiteModel;
use think\App;
use think\exception\ValidateException;
use think\facade\Session;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];
    protected $platform = "";
    protected $is_app = true;
//是否开启操作验证
    protected $open_action_validate = false;
    //忽略应用的动作
    protected $ignore_action = [];

    protected $user_id = 0;
    protected $session_id = "";
    protected $user_model = null;

    protected $share_uid = 0;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
        $auto_platform_info = $this->request->header('platform-info');
        $auto_platform_info_arr = empty($auto_platform_info) ? [] : explode(';',$auto_platform_info);
        //平台
        $this->platform = $auto_platform_info_arr[0]??'';
        $this->is_app = $this->platform=='android' || $this->platform=='ios';
        //分享者id
        $this->share_uid = $auto_platform_info_arr[1]??1;
        //商家id
        $this->mch_id = $auto_platform_info_arr[2]??0;
        //坐标
        $lng_lat = $auto_platform_info_arr[3]??'';
        $lng_lat = empty($lng_lat)?[]:explode('-',$lng_lat);


        if(app()->http->getName()=='admin'){
            $user_model_class =  SysManagerModel::class;

            $user_token = isset($_SERVER['HTTP_USER_TOKEN'])?$_SERVER['HTTP_USER_TOKEN']:'';
            if(empty($user_token)){
                $user_token = input('user_token','','trim');
            }
            $user_token_arr = \app\common\model\SysManagerModel::validUserToken($user_token);
            $user_id = $user_token_arr===false?0:$user_token_arr[1];
            //管理后台
        }elseif(app()->http->getName()=='api'){
            request()->_u_lng = !empty($lng_lat[0]) ? $lng_lat[0] : '114.077347';
            request()->_u_lat = !empty($lng_lat[1]) ? $lng_lat[1] : '22.549401';
            $user_model_class =  UserModel::class;

            $user_token = isset($_SERVER['HTTP_USER_TOKEN'])?$_SERVER['HTTP_USER_TOKEN']:'';
            if(empty($user_token)){
                $user_token = input('user_token','','trim');
            }
            $user_token_arr = \app\common\model\UserModel::validUserToken($user_token);
            $user_id = $user_token_arr===false?0:$user_token_arr[1];
        }else{

            $user_model_class = UserModel::class;
            $user_id = session('user_info.user_id');
            if(empty($user_id)) {
                $this->createSession(0);
            }else{
                $this->createSession($user_id);
            }
//            Session::destroy();
//            dump(session());exit;
        }

//        dump($user_token_arr,$user_token,$user_id);exit;
        if(!empty($user_id)){
            //查询用户信息
            $user_model = $user_model_class::find($user_id);
            if(!empty($user_model)){
//                dump($user_token);exit;
                if(isset($user_token)){ //token签名验证
                    //验证密码
                    $user_token_arr = $user_model_class::validSecPwd($user_model['password'],$user_token);
//                    dump($user_token_arr);exit;
                }
                if(isset($user_token_arr) && $user_token_arr===false){
                    $this->user_model = null;
                    $this->user_id = 0;
                }else{
                    $this->user_model = $user_model;
                    $this->user_id = $user_model['id'];
                }



            }else{
                $this->user_model = null;
                $this->user_id = 0;
            }
        }
        $this->session_id = session('user_info.session_id');
        //检测是否需要登录权限
        //开启了验证
//        dump($this->open_action_validate,$this->ignore_action,$this->user_id,$this->request->action(true));exit;
        if($this->open_action_validate){
            //验证是否忽略了操作验证
            if(empty($this->user_id) && !in_array($this->request->action(true),$this->ignore_action)){
                // 使用think自带异常类抛出异常
                throw new \think\Exception(lang('err_login'), -1);
            }
        }
    }

    protected function createSession($user_id)
    {
        if(!session('?user_info.session_id')){
            session('user_info',[
                'user_id' => 0,
                'session_id' => Session::instance()->getId(),
            ]);
            Session::save();
        }

        session('user_info.user_id', $user_id);
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 响应数据
     * @param int $code 状态码
     * @param string $msg 消息
     * @param array $data
     * @return \think\Response\Json
     * */
    protected function _resData($code=0,$msg='操作失败',array $data=[],$res_code=200,$res_header=[])
    {
        $res_data = [
            'code' => $code,
            'msg'=>$msg,
        ];
        !empty($data) && $res_data['data']= $data;

        return json($res_data,$res_code,$res_header);
    }

}
